#include    <sys/types.h>
#include    <sys/stat.h>
#include    <fcntl.h>
#include    <termios.h>
#include    <stdio.h>
#include    <unistd.h>
#include <string.h>

#define RD_MAX 50
#define RD_TIME 50

static int      Uart_fd_S;
char Buf[RD_MAX]; 
char *path = NULL;


static void Uart_init_S2(void)
{
    struct      termios newtio;
    bzero(&newtio, sizeof(newtio));     /* clear struct for new port settings */

    newtio.c_cflag  = B9600 | CS8 | CLOCAL | CREAD ;
    newtio.c_iflag  = IGNPAR;
    newtio.c_oflag  = 0;
    newtio.c_lflag  = 0;

    newtio.c_cc[VTIME]  = 10;           /* inter-character 10 * 0.1 = 1s*/
    newtio.c_cc[VMIN]   = 8;

    tcflush(Uart_fd_S, TCIFLUSH);
    tcsetattr(Uart_fd_S, TCSANOW, &newtio);
}


static int Uart_open_ttySP0(void)
{
    printf("open /dev/ttyS2");
    Uart_fd_S =   open("/dev/ttyS2", O_RDWR |  O_NOCTTY | O_NONBLOCK | O_NDELAY);

    if (Uart_fd_S <0)
    {
        printf("fail\n");
    }
    else
    {
        printf(" OK!\n");
        printf("B9600 CS8 CLOCAL CREAD\n");
        Uart_init_S2();
    }
    return Uart_fd_S;
}

static int read_datas_tty(int fd, char *rcv_buf, int TimeOut, int Len)  
{  
    int retval;  
    fd_set rfds;  
    struct timeval tv;  
    int ret, pos;  
    tv.tv_sec = TimeOut / 1000;  //set the rcv wait time  
    tv.tv_usec = TimeOut % 1000 * 1000;  //100000us = 0.1s  
  
    pos = 0;  
    while (1)  
    {  
        FD_ZERO(&rfds); 
        FD_SET(fd, &rfds);
        retval = select(fd + 1, &rfds, NULL, NULL, &tv);
        if (retval == -1)  
        {  
            perror("select()");  
            break;  
        }  
        else if (retval)  
        {  
            ret = read(fd, rcv_buf + pos, 1);  
            if (-1 == ret)  
            {  
                break;  
            }  
  
            pos++;  
            if (Len <= pos)  
            {  
                break;  
            }  
        }  
        else  
        {  
            break;  
        }  
    }  
  
    return pos;  
}  

static int send_data_tty(int fd, char *send_buf, int Len)  
{  
    ssize_t ret;  
  
    ret = write(fd, send_buf, Len);  
    if (ret == -1)  
    {  
        printf("write device error\n");  
        return -1;  
    }  
  
    return 1;  
}  

int main(int argc, char *argv[])
{
    int nTmp;

    Uart_fd_S = Uart_open_ttySP0(); 
    if(argc < 2){
        printf("usage: test_uart command\n");
        exit(0);
    }
   
    send_data_tty(Uart_fd_S, argv[1],strlen(argv[1]));
    printf("write > %s\n",argv[1]);
    nTmp = read_datas_tty(Uart_fd_S, Buf, RD_TIME, RD_MAX); 
    if(nTmp > 0){
        printf("read < %s\n",Buf);
    }
    else{
        printf("timeout no ack\n");
    }
    return 0;
}
